// 使用 fetch 走相对路径，通过 Vite 代理转发，避免 axios 实例默认头导致的 multipart 问题

export type DriverImageType =
  | 'id_card_front'
  | 'id_card_back'
  | 'driver_license_front'
  | 'driver_license_back'
  | 'driving_license_front'
  | 'driving_license_back'
  | 'car_images';

export interface UploadDriverImageResult {
  code: string | number;
  msg?: string;
  data: {
    file_path: string; // 例如：/static/uploads/drivers/xxx.jpg（可直接用于 <img src>）
    file_name: string;
    file_size: number;
    upload_time: string;
  };
}

const MAX_SIZE = 5 * 1024 * 1024; // 5MB
const ACCEPT_TYPES = ['image/jpeg', 'image/jpg', 'image/png'];

/**
 * 上传司机相关图片文件（不鉴权）
 * 接口：POST /upload/driver-images (multipart/form-data)
 * 注意：vite 开发代理需将 /upload 代理到后端，否则本地会 404 或跨域
 */
export const uploadDriverImage = async (file: File, type: DriverImageType): Promise<UploadDriverImageResult | any> => {
  // 前置校验
  if (!ACCEPT_TYPES.includes(file.type)) {
    throw new Error('仅支持 jpg/jpeg/png 格式的图片');
  }
  if (file.size > MAX_SIZE) {
    throw new Error('图片大小不能超过 5MB');
  }

  const formData = new FormData();
  formData.append('file', file);
  formData.append('type', type);

  const resp = await fetch('/api/v1/upload/driver-images', {
    method: 'POST',
    body: formData,
    credentials: 'omit',
  });

  if (!resp.ok) {
    const text = await resp.text().catch(() => '');
    throw new Error(`上传失败：${resp.status} ${resp.statusText} ${text}`);
  }

  const data = await resp.json().catch(() => ({}));
  return data;
};
